package com.xywh.dakaqiandao.mvp.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.CoordUtil;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.inner.Point;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xywh.dakaqiandao.R;
import com.xywh.dakaqiandao.di.component.DaggerSouJiJingWeiDuComponent;
import com.xywh.dakaqiandao.di.module.SouJiJingWeiDuModule;
import com.xywh.dakaqiandao.mvp.contract.SouJiJingWeiDuContract;
import com.xywh.dakaqiandao.mvp.presenter.SouJiJingWeiDuPresenter;
import com.xywh.dakaqiandao.mvp.ui.entity.DiQuSheZhi;
import com.xywh.dakaqiandao.mvp.ui.entity.SouJiJingWeiDu;

import org.angmarch.views.NiceSpinner;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.BASE_URL;
import static com.jess.arms.base.BaseConstants.NAME_SPACE;
import static com.jess.arms.utils.Preconditions.checkNotNull;
import static com.xywh.dakaqiandao.mvp.ui.util.GpsUtil.GPS_REQUEST_CODE;


@Route(path = RouterHub.ACTIVITY_SOU_JI_JING_WEI_DU)
public class SouJiJingWeiDuActivity extends BaseActivity<SouJiJingWeiDuPresenter> implements SouJiJingWeiDuContract.View, SensorEventListener, View.OnClickListener, EasyPermissions.PermissionCallbacks {

    public TextView mTime_tv;
    @BindView(R.id.btnRight)
    TextView mBtnRight;
    @BindView(R.id.tv_distance)
    TextView mTvDistance;

    @BindView(R.id.tv_dang_qian_jing_wei_du)
    TextView tvDangQianJingWeiDu;
    @BindView(R.id.btn_shang_chuan)
    Button btnShangChuan;
    @BindView(R.id.nice_spinner)
    NiceSpinner mNiceSpinner;
    private List<Poi> mPoiList;

    /**
     * 规定到达距离范围距离
     */
    private int DISTANCE = 200;
    private MapView mMapView;
    private TextView mDistance_tv;
    private ImageView imgTouXiang;
    private RelativeLayout commit_bt;
    private BaiduMap mBaiduMap;
    private SensorManager mSensorManager;//方向传感器
    private LatLng mDestinationPoint;//目的地坐标点
    private LocationClient client;//定位监听
    private LocationClientOption mOption;//定位属性
    private MyLocationData locData;//定位坐标
    private InfoWindow mInfoWindow;//地图文字位置提醒
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private int mCurrentDirection = 0;
    private double mDistance = 0;
    private LatLng mCenterPos;
    private float mZoomScale = 0; //比例
    private Double lastX = 0.0;
    private String[] permissionsLocation = {Manifest.permission.ACCESS_COARSE_LOCATION};
    /**
     * 处理连续定位的地图UI变化
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            BDLocation location = (BDLocation) msg.obj;
            LatLng LocationPoint = new LatLng(location.getLatitude(), location.getLongitude());
            //打卡范围
//            mDestinationPoint = new LatLng(location.getLatitude() * 1.0001, location.getLongitude() * 1.0001);//假设公司坐标
//            mDestinationPoint = new LatLng(39.916527 * 1.0001, 116.397128 * 1.0001);//假设公司坐标
            mDestinationPoint = new LatLng(location.getLatitude() * 1.000005, location.getLongitude() * 1.000005);//假设公司坐标

//            setCircleOptions();
            //计算两点距离,单位：米
//            mDistance = DistanceUtil.getDistance(mDestinationPoint, LocationPoint);
//            if (mDistance <= DISTANCE) {
//                //显示文字
//                setTextOption(mDestinationPoint, "您已在签到范围内", "#7ED321");
//                //目的地图标
//                setMarkerOptions(mDestinationPoint, R.mipmap.arrive_icon);
//                //按钮颜色
//                commit_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.restaurant_btbg_yellow));
//                mBaiduMap.setMyLocationEnabled(false);
//            } else {
//                setTextOption(LocationPoint, "您不在签到范围之内", "#FF6C6C");
//                setMarkerOptions(mDestinationPoint, R.drawable.restaurant_icon);
//                commit_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.restaurant_btbg_gray));
//                mBaiduMap.setMyLocationEnabled(true);
//            }
            tvDangQianJingWeiDu.setText("经度：" + mCurrentLon + "     纬度：" + mCurrentLat);
            mBaiduMap.setMyLocationEnabled(true);
//            mDistance_tv.setText("距离目的地：" + mDistance + "米");
            //缩放地图
            setMapZoomScale(LocationPoint);
        }
    };


    /***
     * 接收定位结果消息，并显示在地图上
     */
    private BDAbstractLocationListener BDAblistener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //定位方向
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mTvDistance.setText("当前地址：" + location.getAddrStr());

            mPoiList = location.getPoiList();


            //骑手定位
            locData = new MyLocationData.Builder()
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.NORMAL, true, null));
            //更改UI
            Message message = new Message();
            message.obj = location;
            mHandler.sendMessage(message);
        }
    };
    /**
     * 设置系统时间
     */
    private Runnable run = new Runnable() {
        @Override
        public void run() {
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");// HH:mm:ss
//            Date date = new Date(System.currentTimeMillis());//获取当前时间
//            mTime_tv.setText(simpleDateFormat.format(date)); //更新时间
//            mHandler.postDelayed(run, 1000);
        }
    };
    /**
     * 构造广播监听类，监听 SDK key 验证以及网络异常广播
     */
    private SDKReceiver mReceiver;
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private BottomDialogUtil mBottomDialogUtilShare;
    private String imgStr = "";
    private String mSelectRegionName = "";
    private Integer mSelectRegionId;

    @OnClick(R.id.btn_cha_kan_geng_duo_di_zhi)
    void gengDuoDiZhi() {
        showSimpleBottomSheetList();
    }

    // ================================ 生成不同类型的BottomSheet
    private void showSimpleBottomSheetList() {
        if (mPoiList != null && mPoiList.size() > 0) {

            QMUIBottomSheet.BottomListSheetBuilder bottomListSheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(getContext());
            for (int i = 0; i < mPoiList.size(); i++) {
                bottomListSheetBuilder.addItem(mPoiList.get(i).getName());
            }
            bottomListSheetBuilder.setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                @Override
                public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                    dialog.dismiss();
                    Toast.makeText(getContext(), mPoiList.get(position).getName(), Toast.LENGTH_SHORT).show();
                }
            }).build().show();
        } else {
            showMessage("没有更多地址");
        }
    }


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSouJiJingWeiDuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .souJiJingWeiDuModule(new SouJiJingWeiDuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        if (getLocationPermission()) {
            SDKInitializer.initialize(getApplicationContext());//百度地图
            // 注册 SDK 广播监听者
            RegisterBroadcast();
        }

        return R.layout.activity_sou_ji_jing_wei_du; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    private boolean getLocationPermission() {
        if (EasyPermissions.hasPermissions(this, permissionsLocation)) {

            return true;
        } else {

            EasyPermissions.requestPermissions(this, "需要获取定位权限", 104, permissionsLocation);
            return false;
        }

    }

    protected void RegisterBroadcast() {
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK);
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mReceiver = new SDKReceiver();
        registerReceiver(mReceiver, iFilter);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_sou_ji_jing_wei_du));
//        getSouJiJingWeiDuData();
        //        getQianDaoData();
        PhotoUtil.init(this, new FrescoIniter());


        initBaiduMap();     //1、初始化地图

        getLocationClientOption();//2、定位开启

        mHandler.post(run);//设置系统时间

        mDistance_tv = (TextView) findViewById(R.id.distance_tv);
        imgTouXiang = (ImageView) findViewById(R.id.img_tou_xiang);
        mTime_tv = (TextView) findViewById(R.id.arriver_timetv);
        commit_bt = (RelativeLayout) findViewById(R.id.arriver_bt);
        commit_bt.setOnClickListener(this);


        mBtnRight.setText("重新定位");
        mBtnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (GpsUtil.checkGpsIsOpen(SouJiJingWeiDuActivity.this)) {

                showMessage("定位中...");
                client.restart();
//                }
            }
        });

        getRegionList();

//        GpsUtil.checkGpsIsOpen(this);

    }

    /**
     * 初始化地图
     */
    private void initBaiduMap() {
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        mMapView = (MapView) findViewById(R.id.mapview);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);
    }

    /***
     * 定位选项设置
     * @return
     */
    public void getLocationClientOption() {
        mOption = new LocationClientOption();
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        mOption.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
//        mOption.setScanSpan(30000);//可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        mOption.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        mOption.setIsNeedLocationDescribe(true);//可选，设置是否需要地址描述
        mOption.setNeedDeviceDirect(true);//可选，设置是否需要设备方向结果
        mOption.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        mOption.setIgnoreKillProcess(true);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        mOption.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        mOption.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mOption.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        mOption.setOpenGps(true);//可选，默认false，设置是否开启Gps定位
        mOption.setIsNeedAltitude(false);//可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        mOption.setPriority(LocationClientOption.GpsOnly);
        client = new LocationClient(this);
        client.setLocOption(mOption);
        client.registerLocationListener(BDAblistener);
        client.start();
    }

    private void getRegionList() {

        showLoading();

        String methodName = "getCanChangeRegionList";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("getCanChangeRegionListResult").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("-1")) {
                    List<DiQuSheZhi> entityList = new Gson().fromJson(result, new TypeToken<List<DiQuSheZhi>>() {
                    }.getType());

                    if (entityList != null && entityList != null && entityList.size() > 0) {

//                        List<String> dataset = new LinkedList<>(Arrays.asList("One", "Two", "Three", "Four", "Five"));
                        List<String> dataset = new LinkedList<>();
                        List<Integer> datasetIds = new LinkedList<>();

                        for (int i = 0; i < entityList.size(); i++) {
                            dataset.add(entityList.get(i).getRegionName());
                            datasetIds.add(entityList.get(i).getRegionId());
                        }

                        mNiceSpinner.attachDataSource(dataset);
                        mSelectRegionName = dataset.get(0);
                        mSelectRegionId = datasetIds.get(0);
                        mNiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                mSelectRegionName = dataset.get(position);
                                mSelectRegionId = datasetIds.get(position);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                    } else {

                    }

                } else {


                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);

    }
    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    private void getSouJiJingWeiDuData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getSouJiJingWeiDuData(map);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GPS_REQUEST_CODE) {
//            openGPSSEtting();
            client.restart();
        } else {
            PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        if (requestCode == 104) {
            SDKInitializer.initialize(getApplicationContext());//百度地图
            // 注册 SDK 广播监听者
            RegisterBroadcast();
        }
    }

    //设置打卡目标范围圈
    private void setCircleOptions() {
        if (mDestinationPoint == null) return;
        OverlayOptions ooCircle = new CircleOptions().fillColor(0x4057FFF8)
                .center(mDestinationPoint).stroke(new Stroke(1, 0xB6FFFFFF)).radius(DISTANCE);
        mBaiduMap.addOverlay(ooCircle);
    }

    /**
     * 添加地图文字
     *
     * @param point
     * @param str
     * @param color 字体颜色
     */
    private void setTextOption(LatLng point, String str, String color) {
        //使用MakerInfoWindow
        if (point == null) return;
        TextView view = new TextView(getApplicationContext());
        view.setBackgroundResource(R.drawable.map_textbg);
        view.setPadding(50, 23, 50, 0);
        view.setTypeface(Typeface.DEFAULT_BOLD);
        view.setTextSize(14);
        view.setGravity(Gravity.CENTER);
        view.setText(str);
        view.setTextColor(Color.parseColor(color));
        mInfoWindow = new InfoWindow(view, point, 170);
        mBaiduMap.showInfoWindow(mInfoWindow);
    }

    /**
     * 设置marker覆盖物
     *
     * @param ll   坐标
     * @param icon 图标
     */
    private void setMarkerOptions(LatLng ll, int icon) {
        if (ll == null) return;
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(icon);
        MarkerOptions ooD = new MarkerOptions().position(ll).icon(bitmap);
        mBaiduMap.addOverlay(ooD);
    }

    //改变地图缩放
    private void setMapZoomScale(LatLng ll) {
        if (mDestinationPoint == null) {
            mZoomScale = getZoomScale(ll);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(ll, mZoomScale));//缩放
        } else {
            mZoomScale = getZoomScale(ll);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(mCenterPos, mZoomScale));//缩放
        }
    }

    /**
     * 获取地图的中心点和缩放比例
     *
     * @return float
     */
    private float getZoomScale(LatLng LocationPoint) {
        double maxLong;    //最大经度
        double minLong;    //最小经度
        double maxLat;     //最大纬度
        double minLat;     //最小纬度
        List<Double> longItems = new ArrayList<Double>();    //经度集合
        List<Double> latItems = new ArrayList<Double>();     //纬度集合

        if (null != LocationPoint) {
            longItems.add(LocationPoint.longitude);
            latItems.add(LocationPoint.latitude);
        }
        if (null != mDestinationPoint) {
            longItems.add(mDestinationPoint.longitude);
            latItems.add(mDestinationPoint.latitude);
        }

        maxLong = longItems.get(0);    //最大经度
        minLong = longItems.get(0);    //最小经度
        maxLat = latItems.get(0);     //最大纬度
        minLat = latItems.get(0);     //最小纬度

        for (int i = 0; i < longItems.size(); i++) {
            maxLong = Math.max(maxLong, longItems.get(i));   //获取集合中的最大经度
            minLong = Math.min(minLong, longItems.get(i));   //获取集合中的最小经度
        }

        for (int i = 0; i < latItems.size(); i++) {
            maxLat = Math.max(maxLat, latItems.get(i));   //获取集合中的最大纬度
            minLat = Math.min(minLat, latItems.get(i));   //获取集合中的最小纬度
        }
        double latCenter = (maxLat + minLat) / 2;
        double longCenter = (maxLong + minLong) / 2;
        int jl = (int) getDistance(new LatLng(maxLat, maxLong), new LatLng(minLat, minLong));//缩放比例参数
        mCenterPos = new LatLng(latCenter, longCenter);   //获取中心点经纬度
        int[] zoomLevel = {2500000, 2000000, 1000000, 500000, 200000, 100000,
                50000, 25000, 20000, 10000, 5000, 2000, 1000, 500, 100, 50, 20, 0};
        int i;
        for (i = 0; i < 18; i++) {
            if (zoomLevel[i] < jl) {
                break;
            }
        }
        float zoom = i + 4;
        return zoom;
    }

    /**
     * 缩放比例参数
     *
     * @param var0
     * @param var1
     * @return
     */
    public double getDistance(LatLng var0, LatLng var1) {
        if (var0 != null && var1 != null) {
            Point var2 = CoordUtil.ll2point(var0);
            Point var3 = CoordUtil.ll2point(var1);
            return var2 != null && var3 != null ? CoordUtil.getDistance(var2, var3) : -1.0D;
        } else {
            return -1.0D;
        }
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");
    }

    @Override
    protected void onStop() {
        super.onStop();
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.arriver_bt) {

            if (getLocationPermission() && getPermission()) {


//                if (mDistance <= DISTANCE) {
//                    Toast.makeText(this, "打卡成功", Toast.LENGTH_SHORT).show();
//                } else {
//                    Toast.makeText(this, "外勤打卡", Toast.LENGTH_SHORT).show();
//                }
                if (imgStr.length() == 0) {
                    shangChuanTouXiang();
                } else {
                    UpdateRegionInfo();
                }
            }

        }
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            return false;
        }

    }

    private void shangChuanTouXiang() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setVisibility(View.GONE);
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(SouJiJingWeiDuActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    createMaterialForInstoreAuto(compressedPath);


                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(SouJiJingWeiDuActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    createMaterialForInstoreAuto(compressedPath);


                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(SouJiJingWeiDuActivity.this, root);
        mBottomDialogUtilShare.showDiaolog();

    }

    /**
     * UpdateRegionInfo(string regionName, string coordinate)
     */
    private void UpdateRegionInfo() {

        showLoading();

        String methodName = "UpdateRegionInfo";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("regionId", String.valueOf(mSelectRegionId));
        params.put("regionName", mSelectRegionName);
        params.put("coordinate", mCurrentLon + "," + mCurrentLat);
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
//        params.put("image", imgStr);


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("UpdateRegionInfoResult").toString();
                if (result != null && result.equals("success")) {
                    ArmsUtils.makeText(getContext(), "上传经纬度成功");
                } else {
                    ArmsUtils.makeText(getContext(), "上传经纬度失败");
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    private void createMaterialForInstoreAuto(String compressedPath) throws Exception {
        imgStr = ArmsUtils.bitmapPathToBase64String(compressedPath);
        Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
        imgTouXiang.setImageBitmap(bitmap);
//        HashMap<String, String> map = new HashMap<String, String>();
//        map.put("did", String.valueOf(did));
//        map.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
//        map.put("num", String.valueOf(num));
//        map.put("imgStr", String.valueOf(imgStr));
//
//        mPresenter.createMaterialForInstoreAuto(StorageActivity.this, map);
    }

    @Override
    public void getSouJiJingWeiDuDataSuccess(SouJiJingWeiDu entityData) {


    }

    @Override
    protected void onDestroy() {
        // 取消监听 SDK 广播
        unregisterReceiver(mReceiver);
        if (BDAblistener != null) {
            client.unRegisterLocationListener(BDAblistener);

        }
        if (client != null && client.isStarted()) {
            client.stop();
        }
        mMapView.onDestroy();
        mMapView = null;
        mHandler.removeCallbacks(run);
        super.onDestroy();

        PhotoUtil.clearMemoryCaches();
    }

    @OnClick(R.id.btn_shang_chuan)
    public void onViewClicked() {
        UpdateRegionInfo();
    }

    public class SDKReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            String s = intent.getAction();
            String tx = "";

            if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {

                tx = "key 验证出错! 错误码 :" + intent.getIntExtra
                        (SDKInitializer.SDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE, 0)
                        + " ; 请在 AndroidManifest.xml 文件中检查 key 设置";
            } else if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) {
                tx = "key 验证成功! 功能可以正常使用";
            } else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                tx = "网络出错";
            }
            if (tx.contains("错")) {
                AlertDialog.Builder normalDialog =
                        new AlertDialog.Builder(context);
                normalDialog.setTitle("提示");
                normalDialog.setMessage(tx);
                normalDialog.setPositiveButton("确定", null);
                normalDialog.setNegativeButton("关闭", null);
                // 显示
                normalDialog.show();
            } else {
//                Toast.makeText(context, tx, Toast.LENGTH_SHORT).show();
            }

        }
    }
}
